import { CascaderSelect } from '@alifd/next';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { getTopItems, getChildren, itemsByLevel } from './api';
import { CascaderSelectProps } from '@alifd/next/types/cascader-select';
import { flatToTree } from '@/utils/util';

interface DictItemSelectProps extends CascaderSelectProps {
  dictId: string;
  maxLevel?: number;
  /**
   * 是否一次性拉取所有子节点,默认false
   */
  sync?: boolean;
}

function DictTreeSelect({ dictId, maxLevel = 1000, sync, value, ...props }: DictItemSelectProps) {
  const [data, setData] = useState<any[]>([]);
  const flatten = useRef({}).current;

  useEffect(() => {
    (async function fetchData() {
      if (sync) {
        let items = await itemsByLevel(dictId, maxLevel);
        items = items.map(mapper);
        setData(flatToTree(items));
      } else {
        const items = await getTopItems(dictId);
        setData(items.map(mapper));
      }
    })();
  }, []);

  const mapper = useCallback((v) => {
    const item = {
      label: v.name,
      value: v.itemId,
      ...v,
    };
    const level = v.fullId.split(':').length;
    item.isLeaf = level >= maxLevel;
    flatten[v.itemId] = item;
    return item;
  }, [data]);

  const onLoadData = async (v) => {
    const item = flatten[v.itemId];
    if (item.children) return;
    const children = await getChildren(dictId, v.itemId);
    if (children?.length === 0) {
      item.isLeaf = true;
    } else {
      item.children = children.map(mapper);
    }
    setData((prev) => [...prev]);
  };

  return (
    <CascaderSelect
      hasClear
      dataSource={data}
      loadData={onLoadData}
      // style={{ width: '100%' }}
      value={value}
      {...props}
    />
  );
}

export default DictTreeSelect;
